package org.jfk.core.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;



public class StringUtils {


	public static final int BEFORE = 1;

	public static final int AFTER = 2;

	public static final String DEFAULT_PATH_SEPARATOR = ",";

	public static ArrayList strToArrayList(String str) {
		return strToArrayListManager(str, DEFAULT_PATH_SEPARATOR);
	}

	public static ArrayList<String> strToArrayList(String str, String separator) {
		return strToArrayListManager(str, separator);
	}

	private static ArrayList<String> strToArrayListManager(String str,
			String separator) {

		StringTokenizer strTokens = new StringTokenizer(str, separator);
		ArrayList<String> list = new ArrayList<String>();

		while (strTokens.hasMoreTokens()) {
			list.add(strTokens.nextToken().trim());
		}

		return list;
	}

	public static String[] strToStrArray(String str) {
		return strToStrArrayManager(str, DEFAULT_PATH_SEPARATOR);
	}

	public static String[] strToStrArray(String str, String separator) {
		return strToStrArrayManager(str, separator);
	}

	private static String[] strToStrArrayManager(String str, String separator) {

		StringTokenizer strTokens = new StringTokenizer(str, separator);
		String[] strArray = new String[strTokens.countTokens()];
		int i = 0;

		while (strTokens.hasMoreTokens()) {
			strArray[i] = strTokens.nextToken().trim();
			i++;
		}

		return strArray;
	}

	public static Set<String> strToSet(String str) {
		return strToSet(str, DEFAULT_PATH_SEPARATOR);
	}

	public static Set<String> strToSet(String str, String separator) {
		String[] values = strToStrArray(str, separator);
		Set<String> result = new LinkedHashSet<String>();
		for (int i = 0; i < values.length; i++) {
			result.add(values[i]);
		}
		return result;
	}

	public static String ArrayToStr(Object[] array) {
		if (array == null || array.length < 0)
			return null;
		String str = "";
		int _step = 0;
		for (int i = 0; i < array.length; i++) {
			if (_step > 0)
				str += ",";
			str += (String) array[i];
			_step++;
		}
		return str;
	}

	public static String CollectionToStr(Collection<String> coll) {
		StringBuffer sb = new StringBuffer();
		int i = 0;
		for (String string : coll) {
			if (i > 0)
				sb.append(",");
			i++;
			sb.append(string);
		}
		return sb.toString();
	}

	public static String encodingTransfer(String inputString,
			String inencoding, String outencoding) {
		if (inputString == null || inputString.length() == 0)
			return inputString;
		try {
			return new String(inputString.getBytes(outencoding), inencoding);
		} catch (Exception e) {
			return inputString;
		}
	}

	public static String delString(String inputString, String delStrs) {
		if (inputString == null || inputString.length() == 0)
			return inputString;

		String[] strs = strToStrArray(delStrs);
		for (int i = 0; i < strs.length; i++) {
			if (strs[i].equals(""))
				inputString = inputString.replaceAll(" ", "");
			else {
				if (strs[i].compareTo("a") >= 0)
					inputString = replace(inputString, strs[i], "");
				else
					inputString = inputString.replaceAll("\\" + strs[i], "");
			}
		}
		if (subCount(delStrs, ",") > strs.length)
			inputString = inputString.replaceAll("\\,", "");

		return inputString;
	}

	public static String trimLeft(String value) {
		String result = value;
		if (result == null)
			return result;
		char ch[] = result.toCharArray();
		int index = -1;
		for (int i = 0; i < ch.length; i++) {
			if (Character.isWhitespace(ch[i])) {
				index = i;
			} else {
				break;
			}
		}
		if (index != -1) {
			result = result.substring(index + 1);
		}
		return result;
	}

	public static String trimRight(String value) {
		String result = value;
		if (result == null)
			return result;
		char ch[] = result.toCharArray();
		int endIndex = -1;
		for (int i = ch.length - 1; i > -1; i--) {
			if (Character.isWhitespace(ch[i])) {
				endIndex = i;
			} else {
				break;
			}
		}
		if (endIndex != -1) {
			result = result.substring(0, endIndex);
		}
		return result;
	}

	public static boolean isInclude(String parentStr, String subStr) {
		return parentStr.indexOf(subStr) >= 0;
	}

	public static boolean isIncludes(String parentStr, String subStrs) {
		String[] subStrArray = strToStrArray(subStrs);
		for (int j = 0; j < subStrArray.length; j++) {
			String subStr = subStrArray[j];
			if (isInclude(parentStr, subStr))
				return true;
			else
				continue;
		}
		return false;
	}

	public static int subCount(String parentStr, String subStr) {
		int count = 0;

		for (int i = 0; i < (parentStr.length() - subStr.length()); i++) {
			String tempString = parentStr.substring(i, i + subStr.length());
			if (subStr.equals(tempString)) {
				count++;
			}
		}

		return count;
	}

	public static String subString(String parentStr, String startStr,
			String endStr) {
		return parentStr.substring(parentStr.indexOf(startStr)
				+ startStr.length(), parentStr.indexOf(endStr));
	}

	public static List<String> subStringList(String parentStr, String startStr,
			String endStr) {
		List<String> result = new ArrayList<String>();
		List<String> elements = dividToList(parentStr, startStr, endStr);
		for (String element : elements) {
			if (!isIncludes(element, startStr) || !isIncludes(element, endStr))
				continue;
			result.add(subString(element, startStr, endStr));
		}
		return result;

	}

	public static String getUnicodeStr(String inStr) {
		char[] myBuffer = inStr.toCharArray();
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < inStr.length(); i++) {
			byte b = (byte) myBuffer[i];
			short s = (short) myBuffer[i];
			String hexB = Integer.toHexString(b);
			String hexS = Integer.toHexString(s);

			// short value
			sb.append(" \\u");
			sb.append(fillStr(hexS, "0", 4, AFTER));
			// sb.append('\t');
			// Unicode Block
			// sb.append(Character.UnicodeBlock.of(myBuffer[i]));
		}

		return sb.toString();

	}

	public static boolean isJavaIdentifier(String s) {
		if (s.length() == 0 || Character.isJavaIdentifierStart(s.charAt(0)))
			return false;
		for (int i = 0; i < s.length(); i++)
			if (!Character.isJavaIdentifierPart(s.charAt(i)))
				return false;
		return true;
	}


	public static String replaceAll(String str, char oldchar, char newchar) {
		char[] chars = str.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if (chars[i] == oldchar)
				chars[i] = newchar;
		}
		return new String(chars);
	}


	public static String fillStr(String inStr, String fill, int length,
			int direction) {
		if (inStr == null || inStr.length() > length || inStr.length() == 0)
			return inStr;

		StringBuffer tempStr = new StringBuffer("");
		for (int i = 0; i < length - inStr.length(); i++) {
			tempStr.append(fill);
		}

		if (direction == AFTER)
			return new String(tempStr.toString() + inStr);
		else
			return new String(inStr + tempStr.toString());
	}
	public static String replaceLast(String str ,String target, String replacement){
		if (isNull(str) || isNull(target) || isNull(replacement))
			return str;
		String s[] = str.split(target);
		
		if (s.length > 1){
			
			String newStr = "";
			for (int i = 0; i < s.length; i++){
				if (i == s.length - 2)
					newStr = newStr+s[i]+replacement;
				else if (i == s.length - 1)
					newStr = newStr+s[i];
				else
					newStr = newStr+s[i]+target;
			}
			return newStr;
		}else{
			return str;
		}
	}

	public static String replace(String str, String pattern, String replace) {
		int s = 0;
		int e = 0;
		StringBuffer result = new StringBuffer();
		while ((e = str.indexOf(pattern, s)) >= 0) {
			result.append(str.substring(s, e));
			result.append(replace);
			s = e + pattern.length();
		}
		result.append(str.substring(s));

		return result.toString();
	}


	public static List<String> dividToList(String str, String start, String end) {
		if (str == null || str.length() == 0)
			return null;

		int s = 0;
		int e = 0;
		List<String> result = new ArrayList<String>();
		if (isInclude(str, start) && isInclude(str, end)) {
			while ((e = str.indexOf(start, s)) >= 0) {
				result.add(str.substring(s, e));
				s = str.indexOf(end, e) + end.length();
				result.add(str.substring(e, s));
			}
			if (s < str.length())
				result.add(str.substring(s));

			if (s == 0)
				result.add(str);
		} else
			result.add(str);

		return result;
	}


	public static String upperFrist(String string) {
		if (string == null)
			return null;
		String upper = string.toUpperCase();
		return upper.substring(0, 1) + string.substring(1);
	}


	public static String lowerFrist(String string) {
		if (string == null)
			return null;
		String lower = string.toLowerCase();
		return lower.substring(0, 1) + string.substring(1);
	}

	public static String URLEncode(String string, String encode) {
		try {
			return URLEncoder.encode(string, encode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Date StrToDate(String sDate ,String format){
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		try {
			return formatter.parse(sDate);
		} catch (ParseException e) {
			return null;
		}
	}

	public static String DateToStr(Date date, String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(date);
	}


	public static String escapeHtml(String string) {
		if (string == null || string.length() == 0) {
			return "";
		}

		char b;
		char c = 0;
		int i;
		int len = string.length();
		StringBuffer sb = new StringBuffer(len + 4);
		String t;

		for (i = 0; i < len; i += 1) {
			b = c;
			c = string.charAt(i);
			switch (c) {
			case '\\':
			case '"':
				sb.append('\\');
				sb.append(c);
				break;
			case '/':
				if (b == '<') {
					sb.append('\\');
				}
				sb.append(c);
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\r':
				sb.append("\\r");
				break;
			default:
				if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
						|| (c >= '\u2000' && c < '\u2100')) {
					t = "000" + Integer.toHexString(c);
					sb.append("\\u" + t.substring(t.length() - 4));
				} else {
					sb.append(c);
				}
			}
		}

		return sb.toString();
	}


	public static String randomString(int length) {
		if (length < 1) {
			return null;
		}
		Random randGen = new Random();
		char[] numbersAndLetters = ("abcdefghijklmnopqrstuvwxyz"
				+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(51)];
		}
		return new String(randBuffer);
	}

	public static boolean isNull(String s) {
		if (s == null) {
			return true;
		}

		String s1 = s.trim();

		if (s1.length() == 0) {
			return true;
		}

		if ("".equals(s1)) {
			return true;
		}
		if ("null".equals(s1)) {
			return true;
		}
		return false;
	}


	public static String str2HexStr(String str) {

		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;

		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0x0f;
			sb.append(chars[bit]);
			sb.append(' ');
		}
		return sb.toString().trim();
	}


	public static String hexStr2Str(String hexStr) {
		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] bytes = new byte[hexStr.length() / 2];
		int n;

		for (int i = 0; i < bytes.length; i++) {
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return new String(bytes);
	}


	public static String byte2HexStr(byte[] b) {
		String stmp = "";
		StringBuilder sb = new StringBuilder("");
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
			sb.append(" ");
		}
		return sb.toString().toUpperCase().trim();
	}


	public static byte[] hexStr2Bytes(String src) {
		int m = 0, n = 0;
		int l = src.length() / 2;
		//System.out.println(l);
		byte[] ret = new byte[l];
		for (int i = 0; i < l; i++) {
			m = i * 2 + 1;
			n = m + 1;
			ret[i] = Byte.decode("0x" + src.substring(i * 2, m)
					+ src.substring(m, n));
		}
		return ret;
	}


	public static String strToUnicode(String strText) throws Exception {
		char c;
		StringBuilder str = new StringBuilder();
		int intAsc;
		String strHex;
		for (int i = 0; i < strText.length(); i++) {
			c = strText.charAt(i);
			intAsc = (int) c;
			strHex = Integer.toHexString(intAsc);
			if (intAsc > 128)
				str.append("\\u" + strHex);
			else
				str.append("\\u00" + strHex);
		}
		return str.toString();
	}


	public static String unicodeToString(String hex) {
		int t = hex.length() / 6;
		StringBuilder str = new StringBuilder();
		for (int i = 0; i < t; i++) {
			String s = hex.substring(i * 6, (i + 1) * 6);
			String s1 = s.substring(2, 4) + "00";
			String s2 = s.substring(4);
			int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
			char[] chars = Character.toChars(n);
			str.append(new String(chars));
		}
		return str.toString();
	}
	
	public static Timestamp str2Timestamp(String t,String sformat) {
		DateFormat format = new SimpleDateFormat(sformat);
		format.setLenient(false);
		try {
			Timestamp ts = new Timestamp(format.parse(t).getTime());
			return ts;
		} catch (ParseException e) {
//			e.printStackTrace();
			return null;
		}
	}	

	public static void main(String[] args) {
		//System.out.println(StringUtils.randomString(6));
		System.out.println(StringUtils.replaceLast("a_b_c_d", "_", "."));
	}
}
